package com.itlong.cloud.controller.home;

import com.itlong.cloud.POJO.DTO.app.property.app.PropertyAppInspectDTO;
import com.itlong.cloud.POJO.PO.PropertyUserInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.property.app.PropertyAppMessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyUserCacheVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.enumerate.LanguageTypeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode_en.BaseErrorCodeEnumEN;
import com.itlong.cloud.project.app.IAppProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.propertyapp.IPropertyAppMessageServiceClient;
import com.itlong.cloud.user.propertyapp.IPropertyAppUserInfoServiceClient;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      物业APP消息模块控制器
 * </desc>
 *
 * @createDate2020/1/3
 **/
@RestController
@RequestMapping("/home")
@RefreshScope
public class PropertyAppNoticeController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(PropertyAppNoticeController.class);

    @Value("${"+ PlatformConstants.PROPERTY_APP_USER_TOKEN_KEY +"}")
    private String PROPERTY_APP_USER_TOKEN_KEY;

    @Value("${" + PlatformConstants.PROPERTYMANAGE_WEB_URL + "}")
    public String PROPERTY_MANAGE_WEB_URL;

    @Autowired
    private IPropertyAppMessageServiceClient iPropertyAppMessageServiceClient;

    @Autowired
    private IPropertyAppUserInfoServiceClient iPropertyAppUserInfoServiceClient;

    @Autowired
    private IAppProjectServiceClient iAppProjectServiceClient;


    /**
     * <desc>
     *      发布公告
     * </desc>
     *
     * @param token 登录凭证
     * @param projectId 项目id
     * @param title 标题
     * @param postMan 发布人
     * @param content 公告内容
     * @return
     * @Author Zhu.yj
     * @createDate  2020/1/3
     */
    @ResponseBody
    @RequestMapping(value = "/postNotice",method = RequestMethod.POST)
    public Object postNotice(String token,String projectId,String title,String postMan,String content,String language){
        try{
            HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null :request.getAttribute("projectId").toString();
            title = request.getAttribute("title") == null ? null :request.getAttribute("title").toString();
            postMan = request.getAttribute("postMan") == null ? null :request.getAttribute("postMan").toString();
            content = request.getAttribute("content") == null ? null :request.getAttribute("content").toString();
            language = request.getAttribute("language") == null ? null : request.getAttribute("language").toString();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            if (StringUtils.isBlank(projectId) || StringUtils.isBlank(title) || StringUtils.isBlank(content)){
                if (LanguageTypeEnum.CHINESE.getLanguage().equals(language)){
                    return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
                }
                return BaseErrorCodeEnumEN.NOT_PARAM.getErrorCode();
            }
            PropertyUserCacheVO propertyUserCacheVO = iPropertyAppUserInfoServiceClient.retrieve(token);
            iPropertyAppMessageServiceClient.postNotice(projectId,title,postMan,content,propertyUserCacheVO.getUserId());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【物业APP-消息模块-发布公告postNotice】发布公告失败",e);
        }
    }


    /**
     * <desc>
     *      获取公告消息列表
     * </desc>
     *
     * @param token 用户登录凭证
     * @param pageNum
     * @param projectId 项目id
     *
     * @return
     * @Author Zhu.yj
     * @createDate  2020/1/3
     */
    @ResponseBody
    @RequestMapping(value = "/getNoticeList", method = RequestMethod.POST)
    public Object getNoticeList(String token, String pageNum, String projectId){
        try{
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            pageNum = request.getAttribute("pageNum") == null ? null : request.getAttribute("pageNum").toString();
            if (StringUtils.isBlank(projectId) || StringUtils.isBlank(pageNum)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            PropertyUserCacheVO propertyUserCacheVO = iPropertyAppUserInfoServiceClient.retrieve(token);
            Map<String, Object> resultMap = iPropertyAppMessageServiceClient.getNoticeList(projectId,pageNum,propertyUserCacheVO.getUserId());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),resultMap);
        }catch (Exception e){
            throw new DataAccessException("【物业APP-消息模块-获取公告列表getNoticeList】获取公告列表失败",e);
        }


    }
    /**
     * <desc>
     *      获取公告详情，同时记录已读记录
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2020/1/3
     */
    @ResponseBody
    @RequestMapping(value = "/getNoticeDetail",method = RequestMethod.POST)
    public Object getNoticeDetail(String token,String projectId, String noticeId){
        try {
            HttpServletRequest request =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            noticeId = request.getAttribute("noticeId") == null ? null : request.getAttribute("noticeId").toString();
            if (StringUtils.isBlank(projectId) || StringUtils.isBlank(noticeId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //从token中取出用户id
            String userId = UserTokenUtil.tokenDecrypt(token,PROPERTY_APP_USER_TOKEN_KEY);
            Map<String, Object> resultMap = iPropertyAppMessageServiceClient.getNoticeDetail(projectId,noticeId,userId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),resultMap);
        }catch (Exception e){
            throw new DataAccessException("【物业APP-消息模块-获取公告详情getNoticeDetail】获取公告详情失败",e);
        }
    }

    /**
     * <desc>
     *      获取消息中心列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2020/02/17
     */
    @ResponseBody
    @PostMapping(path = "messagesList")
    public Object getMessagesList(HttpServletRequest request){
        try {
            PropertyAppInspectDTO propertyAppInspectDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyAppInspectDTO.class, request);
            if (propertyAppInspectDTO == null || StringUtils.isBlank(propertyAppInspectDTO.getPageNum()) || StringUtils.isBlank(propertyAppInspectDTO.getToken())
                    || StringUtils.isBlank(propertyAppInspectDTO.getProjectId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            PropertyUserCacheVO userCacheVO = iPropertyAppUserInfoServiceClient.retrieve(propertyAppInspectDTO.getToken());
            if (userCacheVO == null) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            String url = PROPERTY_MANAGE_WEB_URL + "pushInfo?";
            propertyAppInspectDTO.setUrl(url);
            propertyAppInspectDTO.setUserId(userCacheVO.getUserId());
            Map<String, Object> data = iPropertyAppMessageServiceClient.getMessagesList(propertyAppInspectDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);
        } catch (Exception e) {
            throw new DataAccessException("【物业APP-消息模块-获取消息中心列表messagesList】获取消息中心列表失败",e);
        }
    }

    /**
     * <desc>
     *      用户读取新消息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2020/02/17
     */
    @ResponseBody
    @PostMapping(path = "readNewMsg")
    public Object readNewMsg(HttpServletRequest request){
        try {
            PropertyAppInspectDTO propertyAppInspectDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyAppInspectDTO.class, request);
            if (propertyAppInspectDTO == null || StringUtils.isBlank(propertyAppInspectDTO.getMsgId()) || StringUtils.isBlank(propertyAppInspectDTO.getToken())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            PropertyUserCacheVO userCacheVO = iPropertyAppUserInfoServiceClient.retrieve(propertyAppInspectDTO.getToken());
            if (userCacheVO == null) {
                return new MessageVO(BaseErrorCodeEnum.PARAM_ERR.getErrorCode());
            }
            iAppProjectServiceClient.readNewMsg(propertyAppInspectDTO.getMsgId(), userCacheVO.getUserId());
            Map<String, String> data = new HashMap<>();
            data.put("readCode", "1");
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);
        } catch (Exception e) {
            throw new DataAccessException("【物业APP-消息模块-用户读取新消息readNewMsg】用户读取新消息失败",e);
        }
    }

}
